package com.songshuai.webapi.permission.interceptor;

import com.songshuai.webapi.baseapi.annotations.ApiAuth;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Slf4j
public class AuthInterceptor implements HandlerInterceptor {


    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {

        boolean verify = true;
        if(handler instanceof HandlerMethod){
            ApiAuth authInfo= ((HandlerMethod) handler).getMethodAnnotation(ApiAuth.class);
            String signature= request.getHeader("signature");
            log.info(signature);
        }
        /*String sign = request.getHeader("sign");
        Long time = StringUtils.isNotBlank(request.getHeader("time"))?Long.valueOf(request.getHeader("time")):0l;

        if (StringUtils.isBlank(sign) || time <= 0) {
            verify = false;
        }
        ConfigSelfs configSelfs = (ConfigSelfs) SpringContextUtil.getBean("configSelfs");
        String oriToken= EncryptUtil.md5(configSelfs.getOfficialtoken()+time);
        if(!oriToken.equalsIgnoreCase(sign)){
            verify = false;
        }
        if(!verify){
            log.info("验证失败！");
            QueryResponse res = new QueryResponse();
            res.setCode(ResultStatus.FAIL.getErrorCode());
            res.setMessage("验证失败！");
            PrintWriter writer = null;
            try {
                response.setCharacterEncoding("utf-8");
                writer = response.getWriter();
                writer.write(JSON.toJSONString(res));
                writer.flush();
            } catch (IOException e) {
                e.printStackTrace();
            }finally {
                if (null != writer) {
                    writer.close();
                }
            }

        }*/

        return verify;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) {

    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) {

    }
}
